package com.frxuexi.park2303.notice

import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.filter
import com.frxuexi.base.entity.NoticeBeanItem
import com.frxuexi.base.http.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class NoticeDataSource(val apiService: ApiService) : PagingSource<Int, NoticeBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, NoticeBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeBeanItem> {
        return withContext(Dispatchers.IO) {
            try {
                val page = params.key ?: 0
                val res = apiService.getNotices(page, 10).first()
                if (res.code == 200) {
                    val nextPage = if (res.data.size == 10) page + 1 else null
                    LoadResult.Page(res.data.filter {
                        it.title.isNotEmpty() && it.content.isNotEmpty()
                    }.sortedByDescending {
                        it.publishTime
                    }, null, nextPage)
                } else {
                    LoadResult.Error(Exception(res.message))
                }
            } catch (e: Exception) {
                LoadResult.Error(java.lang.Exception(e))
            }
        }
    }
}